<template>
  <div class="list-page">
    <EmergencyVerticalTabNav />
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div>
              <el-form-item label="标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入知识点标题" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="知识分类" prop="category">
                <el-input v-model="queryParams.category" placeholder="请输入知识分类" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" class="add-button" @click="handleAdd">新增</el-button>
            </div>
          </el-form>
        </el-card>
      </div>

      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table
          v-loading="loading"
          :data="tableData"
          @selection-change="handleSelectionChange"
          border
          style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="title" label="知识点标题" min-width="150" />
          <el-table-column prop="category" label="知识分类" width="150" align="center" />
          <el-table-column prop="source" label="知识来源" width="150" />
          <el-table-column prop="status" label="状态" width="150" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" :class="['status-tag', `status-${row.status}`]">
                {{ getStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容预览" min-width="180">
            <template #default="scope">
              <div class="content-preview">
                {{ getContentPreview(scope.row.content) }}
                <el-button link type="primary" @click="showContentDetail(scope.row)" class="view-full-btn">
                  完整内容
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="60%"
        center
        destroy-on-close
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-form-item label="知识点标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入知识点标题" />
          </el-form-item>
          <el-form-item label="知识分类" prop="category">
            <el-input v-model="form.category" placeholder="请输入知识分类" />
          </el-form-item>
          <el-form-item label="知识来源" prop="source">
            <el-input v-model="form.source" placeholder="请输入知识来源" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="知识内容" prop="content">
            <div class="editor-container">
              <el-input
                type="textarea"
                v-model="form.content"
                :rows="5"
                placeholder="请输入知识内容（支持HTML格式）"
              />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </template>
      </el-dialog>

      <!-- 内容详情弹窗 -->
      <el-dialog
        v-model="contentDialogVisible"
        title="知识详情"
        width="70%"
        center
        destroy-on-close
        class="custom-dialog content-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ currentContentTitle }}</span>
          </div>
        </template>
        <div class="content-detail-header">
          <div class="content-meta">
            <span class="meta-item"><strong>分类：</strong>{{ currentContentCategory }}</span>
            <span class="meta-item"><strong>来源：</strong>{{ currentContentSource }}</span>
          </div>
        </div>
        <el-divider />
        <div class="content-detail-body" v-html="currentContentHTML"></div>
        <template #footer>
          <el-button @click="contentDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getEmergencyKnowledgeList,
  getEmergencyKnowledgeById,
  addEmergencyKnowledge,
  updateEmergencyKnowledge,
  deleteEmergencyKnowledge
} from "@/api/bridge/command/emergency";
import { useRouter } from "vue-router";
import { Plus, Back } from '@element-plus/icons-vue';
import EmergencyVerticalTabNav from "./components/EmergencyVerticalTabNav.vue";

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const queryFormRef = ref();

// 路由
const router = useRouter();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: null,
  category: null
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref();
const form = ref({
  id: "",
  title: "",
  category: "",
  source: "",
  content: "",
  status: 1 // 默认启用
});

// 内容详情弹窗相关
const contentDialogVisible = ref(false);
const currentContentTitle = ref("");
const currentContentCategory = ref("");
const currentContentSource = ref("");
const currentContentHTML = ref("");

// 表单校验规则
const rules = {
  title: [{ required: true, message: "请输入知识点标题", trigger: "blur" }],
  category: [{ required: true, message: "请输入知识分类", trigger: "blur" }],
  source: [{ required: true, message: "请输入知识来源", trigger: "blur" }],
  content: [{ required: true, message: "请输入知识内容", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }]
};

// 获取内容预览，去除HTML标签并限制长度
const getContentPreview = (content) => {
  if (!content) return "无内容";
  // 去除HTML标签
  const plainText = content.replace(/<[^>]+>/g, "");
  return plainText.length > 50 ? plainText.substring(0, 50) + "..." : plainText;
};

// 显示内容详情
const showContentDetail = (row) => {
  currentContentTitle.value = row.title;
  currentContentCategory.value = row.category;
  currentContentSource.value = row.source;
  
  // 处理HTML内容
  currentContentHTML.value = row.content;
  
  // 如果内容不是HTML格式，则自动添加段落标签
  if (!row.content.includes('<')) {
    currentContentHTML.value = row.content.split('\n')
      .filter(paragraph => paragraph.trim().length > 0)
      .map(paragraph => `<p>${paragraph}</p>`)
      .join('');
  }
  
  contentDialogVisible.value = true;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  return status === 1 ? "success" : "danger";
};

// 获取状态名称
const getStatusName = (status) => {
  return status === 1 ? "启用" : "停用";
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await getEmergencyKnowledgeList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      title: queryParams.title,
      category: queryParams.category
    });
    tableData.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error("获取应急知识列表失败", error);
    ElMessage.error("获取应急知识列表失败");
  } finally {
    loading.value = false;
  }
};

// 多选操作
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
};

// 搜索操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.title = null;
  queryParams.category = null;
  handleQuery();
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = "新增知识条目";
  form.value = {
    id: "",
    title: "",
    category: "",
    source: "",
    content: "",
    status: 1
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  dialogTitle.value = "编辑知识条目";
  try {
    const res = await getEmergencyKnowledgeById(row.id);
    form.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取知识条目详情失败", error);
    ElMessage.error("获取知识条目详情失败");
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除知识条目"${row.title}"吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteEmergencyKnowledge(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除知识条目失败", error);
      ElMessage.error("删除知识条目失败");
    }
  }).catch(() => {
    // 取消删除
  });
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.id) {
          // 编辑
          await updateEmergencyKnowledge(form.value);
          ElMessage.success("更新成功");
        } else {
          // 新增
          await addEmergencyKnowledge(form.value);
          ElMessage.success("新增成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页操作
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

onMounted(() => {
  getList(); // 获取应急知识条目列表
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: $bg-color-overlay;
  padding: 16px;
  border-radius: $border-radius;
}

.search-input {
  width: 300px;
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

.content-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
  gap: 8px;

  .view-full-btn {
    white-space: nowrap;
    flex-shrink: 0;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.btn-group {
  .edit-btn,
  .cancel-btn,
  .save-btn {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 10px 20px;
    border-radius: 6px;
  }

  .edit-btn {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .cancel-btn {
    &:hover {
      background-color: #f4f4f5;
      color: #909399;
    }
  }

  .save-btn {
    padding: 10px 24px;

    &:hover {
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }
  }
}

.disabled-field {
  :deep(.el-input__inner) {
    background-color: #f8f9fa;
    border-color: #e4e7ed;
    color: #909399;
    cursor: not-allowed;
  }
}

.error-message {
  color: red;
  font-size: 14px;
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

.content-dialog {
  .content-detail-header {
    padding: 16px 0;

    .content-meta {
      display: flex;
      gap: 24px;
      color: var(--el-text-color-secondary);
      font-size: 14px;

      .meta-item {
        strong {
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .content-detail-body {
    padding: 20px 0;
    color: var(--el-text-color-primary);
    line-height: 1.8;

    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
      margin-top: 1.5em;
      margin-bottom: 0.5em;
      font-weight: 600;
    }

    :deep(p) {
      margin-bottom: 1em;
    }

    :deep(ul), :deep(ol) {
      padding-left: 2em;
      margin-bottom: 1em;
    }

    :deep(a) {
      color: var(--el-color-primary);
      text-decoration: none;

      &:hover {
        text-decoration: underline;
      }
    }

    :deep(blockquote) {
      border-left: 4px solid var(--el-border-color);
      padding-left: 1em;
      margin-left: 0;
      margin-right: 0;
      color: var(--el-text-color-secondary);
    }

    :deep(img) {
      max-width: 100%;
      height: auto;
      display: block;
      margin: 1em 0;
    }

    :deep(table) {
      width: 100%;
      border-collapse: collapse;
      margin: 1em 0;

      th, td {
        border: 1px solid var(--el-border-color);
        padding: 8px;
        text-align: left;
      }

      th {
        background-color: var(--el-bg-color-page);
      }
    }
  }
}

.editor-container {
  width: 100%;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  overflow: hidden;
}

/* 状态标签特殊样式 */
.status-tag {
  font-weight: bold;
  
  &.status-1 {
    background: var(--el-color-success-light-8) !important;
    color: var(--el-color-success-dark-2) !important;
    border-color: var(--el-color-success) !important;
  }
  
  &.status-0 {
    background: var(--el-color-danger-light-8) !important;
    color: var(--el-color-danger-dark-2) !important;
    border-color: var(--el-color-danger) !important;
  }
}
</style> 